/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * friendsScreen.java
 *
 * Created on Mar 30, 2011, 5:15:12 PM
 */

package forumGUI;

import client.ForumClientListener;
import client.MessagesListener;
import client.TcpClient;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import messaage.*;

/**
 * 
 * @author Olga
 */
public class friendsScreen extends javax.swing.JFrame implements
		MessagesListener {

	private DefaultListModel friendsListModel;
	private TcpClient client;
	private String username;
        private boolean isModerator;

	/** Creates new form friendsScreen */
	public friendsScreen(TcpClient newClient, String newUsername, boolean _isModerator) {

		initComponents();
		this.friendsListModel = new DefaultListModel();
		this.friendsList.setModel(this.friendsListModel);
		this.client = newClient;
		this.username = newUsername;
                this.isModerator = _isModerator;
                this.setBackground();

	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed"
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        friendListLabel = new javax.swing.JLabel();
        addFriendButton = new javax.swing.JButton();
        removeFriendButton = new javax.swing.JButton();
        logoutButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        friendsList = new javax.swing.JList();
        BackToForumsButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        friendListLabel.setFont(new java.awt.Font("Viner Hand ITC", 0, 48)); // NOI18N
        friendListLabel.setText("My friends");

        addFriendButton.setFont(new java.awt.Font("Tempus Sans ITC", 1, 18)); // NOI18N
        addFriendButton.setText("Add friend");
        addFriendButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addFriendButtonActionPerformed(evt);
            }
        });

        removeFriendButton.setFont(new java.awt.Font("Tempus Sans ITC", 1, 18)); // NOI18N
        removeFriendButton.setText("Remove friend");
        removeFriendButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeFriendButtonActionPerformed(evt);
            }
        });

        logoutButton.setFont(new java.awt.Font("Tempus Sans ITC", 1, 18)); // NOI18N
        logoutButton.setText("Logout");
        logoutButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                logoutButtonActionPerformed(evt);
            }
        });

        friendsList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = {};
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        friendsList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(friendsList);

        BackToForumsButton.setFont(new java.awt.Font("Tempus Sans ITC", 1, 18)); // NOI18N
        BackToForumsButton.setText("Back To Forums View");
        BackToForumsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BackToForumsButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(190, Short.MAX_VALUE)
                .addComponent(BackToForumsButton)
                .addGap(123, 123, 123)
                .addComponent(logoutButton)
                .addGap(19, 19, 19))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(114, 114, 114)
                .addComponent(addFriendButton, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(removeFriendButton, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(180, 180, 180))
            .addGroup(layout.createSequentialGroup()
                .addGap(220, 220, 220)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(285, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(191, 191, 191)
                .addComponent(friendListLabel)
                .addContainerGap(228, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(friendListLabel)
                .addGap(39, 39, 39)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(40, 40, 40)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(removeFriendButton)
                    .addComponent(addFriendButton))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BackToForumsButton)
                    .addComponent(logoutButton))
                .addContainerGap(26, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

        private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
            this.setDefaultCloseOperation(this.DO_NOTHING_ON_CLOSE);
            DisconnectMsg msg = new DisconnectMsg(username);  //TODO change the username to send
            this.client.sendMessage(msg);
        }//GEN-LAST:event_formWindowClosed

        private void BackToForumsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BackToForumsButtonActionPerformed
            forumsScreen fs = new forumsScreen(this.client, this.username, this.isModerator);
            ForumClientListener tempListener = (ForumClientListener) this.client.getListener();
            tempListener.getConnector().addListener(fs);
            this.client.sendMessage(new GetListOfForumsMsg((this.username)));
            tempListener.getConnector().removeListener(this);
            this.setVisible(false);
            
        }//GEN-LAST:event_BackToForumsButtonActionPerformed

	private void addFriendButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_addFriendButtonActionPerformed
		AddFriendScreen add = new AddFriendScreen(this.client, this.username);
		add.setVisible(true);
	}// GEN-LAST:event_addFriendButtonActionPerformed

	private void removeFriendButtonActionPerformed(
			java.awt.event.ActionEvent evt) {// GEN-FIRST:event_removeFriendButtonActionPerformed
		int selectedIndex = this.friendsList.getSelectedIndex();
		if (selectedIndex > -1) {
			RemoveFriendMsg msg = new RemoveFriendMsg(this.username,
					(String) this.friendsListModel.get(selectedIndex));
			this.client.sendMessage(msg);
		} else
			JOptionPane.showMessageDialog(this,
					"You have to select a friend to remove");
	}// GEN-LAST:event_removeFriendButtonActionPerformed

	private void logoutButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_logoutButtonActionPerformed
		LogoutMsg msg = new LogoutMsg(username);
		this.client.sendMessage(msg);
	}// GEN-LAST:event_logoutButtonActionPerformed

              public void setBackground()
    {
        Container con =this.getContentPane();
        JPanel panelBgImg;
        con.setLayout(null);
        final String photoPath = "src/images/screen.jpg";
        ImageIcon imh = new ImageIcon(photoPath);
//        setSize(imh.getIconWidth(), imh.getIconHeight());

        panelBgImg = new JPanel()
        {
            public void paintComponent(Graphics g)
            {
                Image img = new ImageIcon(photoPath).getImage();

                Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
                setPreferredSize(size);
                setMinimumSize(size);
                setMaximumSize(size);
                setSize(size);
                setLayout(null);
                g.drawImage(img, 0, 0, null);
            }
        };

        con.add(panelBgImg);
        panelBgImg.setBounds(0, 0, imh.getIconWidth(), imh.getIconHeight());

    }
	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				// new friendsScreen().setVisible(true);
			}
		});
	}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BackToForumsButton;
    private javax.swing.JButton addFriendButton;
    private javax.swing.JLabel friendListLabel;
    private javax.swing.JList friendsList;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton logoutButton;
    private javax.swing.JButton removeFriendButton;
    // End of variables declaration//GEN-END:variables
	@Override
	public void connected(ConnectedMsg msg) {
	}

	@Override
	public void disconnected(DisconnectedMsg msg) {
        ForumClientListener tempListener = (ForumClientListener) this.client.getListener();
        tempListener.getConnector().removeListener(this);
            this.dispose();
	}

	@Override
	public void errorMessage(ErrorMsg msg) {
		String body = msg.getBody();
		JOptionPane.showMessageDialog(this, body);
	}

	@Override
	public void registered(RegisteredMsg msg) {
	}

	@Override
	public void loggedIn(LoggedInMsg msg) {
	}

	@Override
	public void loggedOff(LoggedOffMsg msg) {
        ForumClientListener tempListener = (ForumClientListener) this.client.getListener();
        tempListener.getConnector().removeListener(this);
		this.setVisible(false);
		
		MainScreen ms = new MainScreen(client);
		ms.setVisible(true);

	}

	@Override
	public void gotListOfForums(GotListOfForumsMsg msg) {
	}

	@Override
	public void gotTopicsOfForum(GotTopicsOfForumMsg msg) {
	}

	@Override
	public void gotThread(GotThreadMsg msg) {
	}

	@Override
	public void addedPost(AddedPostMsg msg) {
		if (msg.isFriend())
			JOptionPane.showMessageDialog(this, "Your friend added post");
	}

	@Override
	public void createdThread(CreatedThreadMsg msg) {
		if (msg.getIsFriend())
			JOptionPane.showMessageDialog(this, "Your friend added thread");
	}

	@Override
	public void addedForum(AddedForumMsg msg) {
		if (msg.isFriend())
			JOptionPane.showMessageDialog(this, "Your friend added forum");		
	}

	@Override
	public void removedForum(RemovedForumMsg msg) {
	}

	@Override
	public void editedPost(EditedPostMsg msg) {
	}

	@Override
	public void removedUser(RemovedUserMsg msg) {
		if (msg.getUsername().equalsIgnoreCase(this.username)){
                    JOptionPane.showMessageDialog(this, "You have been removed from the forum!!!");
                    ForumClientListener tempListener = (ForumClientListener) this.client.getListener();
                    tempListener.getConnector().removeListener(this);
                    this.dispose();
                }

	}

	@Override
	public void removedThread(RemovedThreadMsg msg) {
	}

	@Override
	public void removedPost(RemovedPostMsg msg) {
	}

	@Override
	public void addedFriend(AddedFriendMsg msg) {
            if (msg.getUsername().equalsIgnoreCase(this.username)){
		String nameOfFriend = msg.getFriendName();
		this.friendsListModel.addElement(nameOfFriend);
            }
	}

	@Override
	public void removedFriend(RemovedFriendMsg msg) {
                if (msg.getUsername().equalsIgnoreCase(this.username)){
                    this.friendsListModel.removeElement(msg.getFriendName());
            }
	}

	@Override
	public void gotFriendsList(GotFriendsListMsg msg) {
                System.out.println("arrived to gotFriendList");
		ArrayList<String> listOfFriends = msg.getListOfFriends();
                System.out.println(listOfFriends.size());
                for (int i = 0; i < listOfFriends.size(); i++){
                    System.out.println(listOfFriends.get(i));
                    this.friendsListModel.addElement(listOfFriends.get(i));
                }
                this.setVisible(true);
	}

}
